package dao.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import dao.BoardDao;
import domain.Board;
import domain.Question;

public class BoardDaoImpl implements BoardDao {

	public List<Board> list() {
		try {
			Session session = HibernateSessionFactory.getSession();
			List<Board> list = null;
			Query qr = session.createQuery("from Board");
			list = qr.list();
			if (session != null)
				session.close();

			return list;
		} catch (HibernateException e) {
			e.printStackTrace();
			return null;
		}
	}

	public void save(Board board) {
		try {
			Session session;
			session = null;
			Transaction tx = null;
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.save(board);
			session.flush();
			tx.commit();
			if (session != null)
				session.close();

		} catch (HibernateException e) {

			e.printStackTrace();
		}

	}

	public void update(Board board) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.merge(board);
		transaction.commit();
		if (session != null)
			session.close();

	}

	public Board findById(int boardId) {
		Session session = HibernateSessionFactory.getSession();
		Board btemp = (Board) session.get(Board.class, boardId);
		if (session != null)
			session.close();
		return btemp;
	}

	public void delete(int boardId) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		session.delete(session.get(Board.class, boardId));
		transaction.commit();
		if (session != null)
			session.close();

	}

	public Set<Question> getQuestionSet(int boardId) {
		if (this.findById(boardId) != null) {
			Session session = HibernateSessionFactory.getSession();
			Board boardTemp = (Board) session.load(Board.class, boardId);
			Set<Question> QuestionTemp = null;
			if (boardTemp.getQuestions() != null)
				QuestionTemp = boardTemp.getQuestions();
			if (session != null)
				session.close();
			return QuestionTemp;
		}
		return null;
	}

	public Iterator<Question> getQuestionIterator(int boardId) {

		if (this.findById(boardId) != null) {
			Session session = HibernateSessionFactory.getSession();
			Board boardTemp = (Board) session.load(Board.class, boardId);
			Set<Question> QuestionTemp = boardTemp.getQuestions();
			Iterator<Question> iter = null;
			if (QuestionTemp != null)
				iter = QuestionTemp.iterator();
			if (session != null)
				session.close();
			return iter;
		}
		return null;
	}
}